<script>
import dayjs from "dayjs";
import { ElButton, ElNotification } from "element-plus"
import TodoForm from "./TodoForm.vue";

export default {
  components: {
    TodoForm,
    ElButton
  },
  props: {
    todo: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      showModify: false,
    };
  },
  emits: ["modify-todo"],
  computed: {
    color() {
      return this.todo.priority === "normal"
        ? "bg-green-500"
        : this.todo.priority == "important"
          ? "bg-blue-500"
          : "bg-red-500";
    },
    created_at() {
      return dayjs(this.todo.created_at).format("YYYY-MM-DD HH:mm");
    },
    finished_at() {
      return this.todo.finished_at
        ? dayjs(this.todo.finished_at).format("YYYY-MM-DD HH:mm")
        : "未完成";
    },
  },
  methods: {
    async handleFinish() {
      const { data } = await this.$request(`/todos/finish/${this.todo.id}`, {
        method: "PUT",
      });
      if (data.success) {
        this.$emit("modify-todo", data.todo)
      } else {
        ElNotification({
          title: '错误',
          message: data.message,
          type: 'error',
        })
      }
    }
  }
};
</script>
<template>
  <ElCard class="my-2 mx-4">
    <template #header>
      <div class="flex justify-between">
        <div class="flex items-center">
          <div class="w-4 h-4 rounded-full mr-2" :class="color"></div>
          <span class="font-bold text-2xl text-gray-500">
            {{ todo.title }}
          </span>
        </div>
        <div>
          <el-popconfirm title="你确定完成该代办？" @confirm="handleFinish">
            <template #reference>
              <el-button class="" type="primary" :disabled="Boolean(todo.finished_at)">完成</el-button>
            </template>
          </el-popconfirm>
          <!-- <el-button class="" type="primary">完成</el-button> -->
          <el-button class="" type="success" @click="showModify = true" :disabled="!!todo.finished_at">修改</el-button>
          <ElButton type="danger">删除</ElButton>
        </div>
      </div>
    </template>
    <p>{{ todo.description }}</p>
    <div class="flex">
      <div class="text-white bg-yellow-500 p-2 m-2 rounded-md">
        {{ created_at }}
      </div>
      <div class="text-white bg-yellow-500 p-2 m-2 rounded-md">
        {{ finished_at }}
      </div>
    </div>
    <TodoForm title="修改代办" v-model="showModify" :todo="todo"
      @modify-todo="$emit('modify-todo', $event), (showModify = false)" />
  </ElCard>
</template>
